type Unit = "B" | "KB" | "MB" | "GB" | "TB" | "PB"
  | "KiB" | "MiB" | "GiB" | "TiB" | "PiB";

const DECIMAL_UNITS: Unit[] = ["B", "KB", "MB", "GB", "TB", "PB"];
const BINARY_UNITS: Unit[] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];

/**
 * 文件大小单位转换
 * @param value 数值
 * @param from 源单位
 * @param to 目标单位
 */
export function convertFileSize(value: number, from: Unit, to: Unit): number {
  // 先转换成字节数
  let bytes: number;

  if (DECIMAL_UNITS.includes(from)) {
    bytes = value * Math.pow(1000, DECIMAL_UNITS.indexOf(from));
  } else {
    bytes = value * Math.pow(1024, BINARY_UNITS.indexOf(from));
  }

  // 从字节数转换到目标单位
  if (DECIMAL_UNITS.includes(to)) {
    return bytes / Math.pow(1000, DECIMAL_UNITS.indexOf(to));
  } else {
    return bytes / Math.pow(1024, BINARY_UNITS.indexOf(to));
  }
}

/**
 * 自动格式化成合适的单位（默认十进制）
 * @param bytes 字节数
 * @param useBinary 是否使用二进制单位（默认为 false）
 */
export function formatFileSize(bytes: number, useBinary = false): string {
  const units = useBinary ? BINARY_UNITS : DECIMAL_UNITS;
  const step = useBinary ? 1024 : 1000;

  let i = 0;
  let size = bytes;

  while (size >= step && i < units.length - 1) {
    size /= step;
    i++;
  }

  return `${size.toFixed(2)} ${units[i]}`;
}

